<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数组降维</title>
</head>
<body>
<script>

    // concat
    function myFlat(array) {
        return array.reduce((pre, cur) => {
            if (Array.isArray(cur)) {
                return pre.concat(myFlat(cur))
            } else {
                return pre.concat(cur)
            }
        }, [])
    }

    // stack + rest运算符
    function myFlatStack(array) {
        const stack = [].concat(array);
        const res = []
        while (stack.length) {
            const x = stack.pop();
            if (Array.isArray(x)) {
                stack.push(...x)
            } else {
                res.unshift(x)
            }
        }
        return res;
    }

    // split
    // 类型会有错误，无法使用
    function splitFlat(array) {
        return (array + "").split(",")
    }

    // es6
    function flatEs6(array) {
        return array.flat(Infinity);
    }

    const array = [1, 2, [3, [8, [3, 2, 1], {name: "student1"}, 7], 4, 7, [1, {name: "student2"}, 3]], 3, 7]
    console.log("++++++++++++++++++")
    console.log("array", array)
    console.log("++++++++++++++++++")
    console.log("es6实现", flatEs6(array));
    console.log("++++++++++++++++++")
    console.log("reduce concat实现", myFlat(array));
    console.log("++++++++++++++++++")
    console.log("stack concat", myFlatStack(array));
    console.log("++++++++++++++++++")
    console.log("splitFlat", splitFlat(array));
    console.log("++++++++++++++++++")
</script>
</body>
</html>
